#include "GameObjectManager.h"

GameObjectManager::GameObjectManager()
{
}

GameObjectManager::~GameObjectManager()
{
	clearGameObjects();
}

void GameObjectManager::update(const GameTime& p_gameTime)
{
	if(!m_queueList.empty())
	{
		for(auto it = m_queueList.begin(); it != m_queueList.end(); it++)
		{
			m_gameObjects.push_back((*it));
		}
		m_queueList.clear();
	}

	if(!m_removeGameObjects.empty())
	{
		for(auto it = m_removeGameObjects.begin(); it != m_removeGameObjects.end(); it++)
		{
			remove((*it));
		}
		m_removeGameObjects.clear();
	}

	for(auto it = m_gameObjects.begin(); it != m_gameObjects.end(); it++)
	{
		(*it)->update(p_gameTime);
	}
}

inline void GameObjectManager::remove(GameObject* p_gameObject)
{
	for(auto it = m_gameObjects.begin(); it != m_gameObjects.end(); it++)
	{
		if((*it) == p_gameObject)
		{
			m_gameObjects.erase(it);
			delete p_gameObject;
			break;
		}
	}
}

void GameObjectManager::clearGameObjects()
{
	if(!m_gameObjects.empty())
	{
		for(auto it = m_gameObjects.begin(); it != m_gameObjects.end(); it++)
		{
			delete (*it);
			(*it) = nullptr;
		}
		m_gameObjects.clear();
	}



	m_removeGameObjects.clear();
}

GameObject* GameObjectManager::getGameObject(const std::string& p_name)
{
	for (auto it = m_gameObjects.begin(); it != m_gameObjects.end(); it++)
	{
		if ((*it)->getName() == p_name)
			return (*it);
	}
	return nullptr;
}